# Maintainer: David Macek <david.macek.0@gmail.com>
# Contributor (Arch Linux): Gustavo Alvarez <sl1pkn07@gmail.com>
# Contributor: Felix Huettner <huettner94@gmx.de>

_realname=lpeg
pkgbase=mingw-w64-lua-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-lua-${_realname}"
         "${MINGW_PACKAGE_PREFIX}-lua51-${_realname}")
pkgver=1.0.2
pkgrel=1
arch=('any')
url='http://www.inf.puc-rio.br/~roberto/lpeg/'
license=('MIT')
makedepends=("${MINGW_PACKAGE_PREFIX}-lua"
             "${MINGW_PACKAGE_PREFIX}-lua51"
             "${MINGW_PACKAGE_PREFIX}-gcc")
source=("http://www.inf.puc-rio.br/~roberto/${_realname}/${_realname}-${pkgver}.tar.gz"
        #${_realname}-${pkgver}.tar.gz::https://github.com/lua/lpeg/archive/${pkgver}.tar.gz
        "lpeg-0.12-makefile.patch"
        "LICENSE")
sha256sums=('48d66576051b6c78388faad09b70493093264588fcd0f258ddaab1cdd4a15ffe'
            '3f6c283041a747a53cb2132f80a0a239b9b6fa16beab24c8a076d00178a3b776'
            '6be7688c9c648e7c7cde693081be938c869a10aa4de09fe0a4c4c1d66b3cf03d')

prepare() {
  cd "${_realname}-${pkgver}"
  patch -p1 -i "${srcdir}/lpeg-0.12-makefile.patch"
  sed -i 's/lpeg.so/lpeg.dll/' makefile

  mkdir -p "${srcdir}/build-${CARCH}" "${srcdir}/build-51-${CARCH}"
  cp -rf * "${srcdir}/build-${CARCH}"
  sed -i 's/env lua5.1/env lua/' "${srcdir}/build-${CARCH}/test.lua"
  cp -rf * "${srcdir}/build-51-${CARCH}"
}

build() {
  cd "${srcdir}/build-${CARCH}"
  make LUADIR=${MINGW_PREFIX}/include LDFLAGS="$(pkg-config lua --libs)"

  cd "${srcdir}/build-51-${CARCH}"
  make LUADIR=${MINGW_PREFIX}/include/lua5.1 LDFLAGS="$(pkg-config lua5.1 --libs)"
}

check() {
  cd "${srcdir}/build-${CARCH}"
  make test

  cd "${srcdir}/build-51-${CARCH}"
  make test
}

package_mingw-w64-lua-lpeg() {
  pkgdesc='Pattern-matching library for Lua (mingw-w64)'
  depends=("${MINGW_PACKAGE_PREFIX}-lua")

  cd "${srcdir}/build-${CARCH}"

  local luaver=$(pkg-config lua --modversion | sed -r 's/^([0-9]+[.][0-9]+)[.][0-9]+$/\1/')
  install -Dm755 lpeg.dll "${pkgdir}${MINGW_PREFIX}/lib/lua/${luaver}/lpeg.dll"
  install -Dm644 re.lua "${pkgdir}${MINGW_PREFIX}/share/lua/${luaver}/re.lua"
  install -Dm644 "${srcdir}/LICENSE" "${pkgdir}${MINGW_PREFIX}/share/licenses/lua-lpeg/LICENSE"
}

package_mingw-w64-lua51-lpeg() {
  pkgdesc='Pattern-matching library for Lua 5.1 (mingw-w64)'
  depends=("${MINGW_PACKAGE_PREFIX}-lua51")

  cd "${srcdir}/build-51-${CARCH}"
  install -Dm755 lpeg.dll "${pkgdir}${MINGW_PREFIX}/lib/lua/5.1/lpeg.dll"
  install -Dm644 re.lua "${pkgdir}${MINGW_PREFIX}/share/lua/5.1/re.lua"
  install -Dm644 "${srcdir}/LICENSE" "${pkgdir}${MINGW_PREFIX}/share/licenses/lua51-lpeg/LICENSE"
}

package_mingw-w64-i686-lua-lpeg() {
  package_mingw-w64-lua-lpeg
}

package_mingw-w64-x86_64-lua-lpeg() {
    package_mingw-w64-lua-lpeg
}

package_mingw-w64-i686-lua51-lpeg() {
    package_mingw-w64-lua51-lpeg
}

package_mingw-w64-x86_64-lua51-lpeg() {
    package_mingw-w64-lua51-lpeg
}
